import sys
import os

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database

class MaintenanceQuery:
    def __init__(self):
        self.db = Database()
    
    def query_all_maintenance(self):
        """
        查询所有维修记录
        
        返回:
            list: 维修记录列表
        """
        try:
            self.db.connect()
            self.db.cursor.execute(
                """SELECT m.id, d.building, d.room_number, m.issue_description, 
                   m.report_date, m.status, m.resolved_date 
                   FROM maintenance m 
                   JOIN dormitory d ON m.dormitory_id = d.id 
                   ORDER BY m.report_date DESC"""
            )
            maintenance_records = self.db.cursor.fetchall()
            return maintenance_records
        except Exception as e:
            print(f"错误：查询维修记录时发生错误 - {str(e)}")
            return []
        finally:
            self.db.close()
    
    def query_maintenance_by_dormitory(self, dormitory_id):
        """
        根据宿舍ID查询维修记录
        
        参数:
            dormitory_id (int): 宿舍ID
            
        返回:
            list: 维修记录列表
        """
        try:
            self.db.connect()
            
            # 检查宿舍是否存在
            self.db.cursor.execute(
                "SELECT id, building, room_number FROM dormitory WHERE id = ?",
                (dormitory_id,)
            )
            dormitory = self.db.cursor.fetchone()
            
            if not dormitory:
                print(f"错误：ID为 {dormitory_id} 的宿舍不存在")
                return [], None
            
            self.db.cursor.execute(
                """SELECT m.id, d.building, d.room_number, m.issue_description, 
                   m.report_date, m.status, m.resolved_date 
                   FROM maintenance m 
                   JOIN dormitory d ON m.dormitory_id = d.id 
                   WHERE m.dormitory_id = ? 
                   ORDER BY m.report_date DESC""",
                (dormitory_id,)
            )
            maintenance_records = self.db.cursor.fetchall()
            return maintenance_records, f"{dormitory[1]}-{dormitory[2]}"
        except Exception as e:
            print(f"错误：查询维修记录时发生错误 - {str(e)}")
            return [], None
        finally:
            self.db.close()
    
    def query_maintenance_by_status(self, status):
        """
        根据状态查询维修记录
        
        参数:
            status (str): 维修状态 (pending, in_progress, completed)
            
        返回:
            list: 维修记录列表
        """
        try:
            self.db.connect()
            self.db.cursor.execute(
                """SELECT m.id, d.building, d.room_number, m.issue_description, 
                   m.report_date, m.status, m.resolved_date 
                   FROM maintenance m 
                   JOIN dormitory d ON m.dormitory_id = d.id 
                   WHERE m.status = ? 
                   ORDER BY m.report_date DESC""",
                (status,)
            )
            maintenance_records = self.db.cursor.fetchall()
            return maintenance_records
        except Exception as e:
            print(f"错误：查询维修记录时发生错误 - {str(e)}")
            return []
        finally:
            self.db.close()

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    query = MaintenanceQuery()
    
    print("===== 维修记录查询 =====")
    print("1. 查询所有维修记录")
    print("2. 根据宿舍ID查询维修记录")
    print("3. 根据维修状态查询记录")
    
    choice = input("请选择查询方式 (1-3): ")
    
    if choice == '1':
        records = query.query_all_maintenance()
        if records:
            print("\n记录ID\t宿舍\t\t问题描述\t\t报修时间\t\t状态\t\t解决时间")
            for record in records:
                resolved_date = record[6] if record[6] else "未解决"
                status_display = "待处理" if record[5] == 'pending' else "处理中" if record[5] == 'in_progress' else "已完成" if record[5] == 'completed' else record[5]
                print(f"{record[0]}\t{record[1]}-{record[2]}\t{record[3][:10]}...\t{record[4]}\t{status_display}\t{resolved_date}")
        else:
            print("没有找到任何维修记录")
    
    elif choice == '2':
        try:
            dormitory_id = int(input("请输入宿舍ID: "))
            records, dormitory_name = query.query_maintenance_by_dormitory(dormitory_id)
            
            if records and dormitory_name:
                print(f"\n宿舍 {dormitory_name} 的维修记录:")
                print("记录ID\t问题描述\t\t报修时间\t\t状态\t\t解决时间")
                for record in records:
                    resolved_date = record[6] if record[6] else "未解决"
                    status_display = "待处理" if record[5] == 'pending' else "处理中" if record[5] == 'in_progress' else "已完成" if record[5] == 'completed' else record[5]
                    print(f"{record[0]}\t{record[3][:15]}...\t{record[4]}\t{status_display}\t{resolved_date}")
            elif dormitory_name:
                print(f"宿舍 {dormitory_name} 没有维修记录")
        except ValueError:
            print("错误：宿舍ID必须是数字")
    
    elif choice == '3':
        print("\n状态选项:")
        print("1. pending - 待处理")
        print("2. in_progress - 处理中")
        print("3. completed - 已完成")
        
        status_choice = input("请选择状态 (1-3): ")
        
        status = None
        if status_choice == '1':
            status = 'pending'
            status_display = "待处理"
        elif status_choice == '2':
            status = 'in_progress'
            status_display = "处理中"
        elif status_choice == '3':
            status = 'completed'
            status_display = "已完成"
        else:
            print("错误：无效的状态选择")
            exit()
        
        records = query.query_maintenance_by_status(status)
        if records:
            print(f"\n状态为 {status_display} 的维修记录:")
            print("记录ID\t宿舍\t\t问题描述\t\t报修时间\t\t解决时间")
            for record in records:
                resolved_date = record[6] if record[6] else "未解决"
                print(f"{record[0]}\t{record[1]}-{record[2]}\t{record[3][:10]}...\t{record[4]}\t{resolved_date}")
        else:
            print(f"没有找到状态为 {status_display} 的维修记录")
    
    else:
        print("无效的选择")